package com.junqson.je.msg.service;

import com.junqson.je.common.exception.BizException;
import com.junqson.je.common.model.dto.MailDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/1/31 19:38
 * @Version 1.0
 */
@Service
@Slf4j
public class MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Value("${spring.mail.properties.mail.from}")
    private String from;


    /**
     * 发送邮件
     * TODO: 发送失败考虑重发、告警，或者短信兜底
     */
    @Async
    public void sendMail(MailDTO mailDTO) {
        try {
            checkMail(mailDTO); //1.检测邮件
            sendMimeMail(mailDTO); //2.发送邮件
//            return saveMail(mailVo); //3.保存邮件
        } catch (Exception e) {
            log.error("发送邮件失败:", e);//打印错误信息
            throw e;
        }

    }

    //检测邮件信息类
    private void checkMail(MailDTO mailDTO) {
        if (StringUtils.isEmpty(mailDTO.getTo())) {
            throw new BizException("邮件收信人不能为空");
        }
        if (StringUtils.isEmpty(mailDTO.getSubject())) {
            throw new BizException("邮件主题不能为空");
        }
        if (StringUtils.isEmpty(mailDTO.getText())) {
            throw new BizException("邮件内容不能为空");
        }
    }

    //构建复杂邮件信息类
    private void sendMimeMail(MailDTO mailDTO) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true表示支持复杂类型
            mailDTO.setFrom(from);//邮件发信人从配置项读取
            messageHelper.setFrom(mailDTO.getFrom());//邮件发信人
            messageHelper.setTo(mailDTO.getTo().split(","));//邮件收信人
            messageHelper.setSubject(mailDTO.getSubject());//邮件主题
            messageHelper.setText(mailDTO.getText());//邮件内容
            if (!StringUtils.isEmpty(mailDTO.getCc())) {//抄送
                messageHelper.setCc(mailDTO.getCc().split(","));
            }
            if (!StringUtils.isEmpty(mailDTO.getBcc())) {//密送
                messageHelper.setCc(mailDTO.getBcc().split(","));
            }
//            if (mailVo.getMultipartFiles() != null) {//添加邮件附件
//                for (MultipartFile multipartFile : mailVo.getMultipartFiles()) {
//                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
//                }
//            }
            if (mailDTO.getSentDate() == null) {//发送时间
                mailDTO.setSentDate(new Date());
                messageHelper.setSentDate(mailDTO.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());//正式发送邮件
            log.info("发送邮件成功：{}->{}", mailDTO.getFrom(), mailDTO.getTo());
        } catch (Exception e) {
            throw new BizException(e.getMessage());//发送失败
        }
    }

//    //保存邮件
//    private MailVo saveMail(MailVo mailVo) {
//        //将邮件保存到数据库..
//        return mailVo;
//    }

//    //获取邮件发信人
//    public String getMailSendFrom() {
//        return mailSender.getJavaMailProperties().getProperty("from");
//    }
}
